package com.cyl.chat.controller;


import com.cyl.chat.service.BaiduWenxinService;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
@RequestMapping(produces = "application/json;charset=UTF-8")
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Autowired
    private BaiduWenxinService baiduWenxinService;


    @PostMapping("/chat")
    public String chat(@RequestBody Map<String, String> request) {
        String prompt = request.get("prompt");
        String response = null;
        try {
            // 将返回值赋给 response 变量
            response = baiduWenxinService.chat(prompt);
        } catch (IOException e) {
            // 使用日志框架记录异常信息
            logger.error("聊天请求发生异常", e);
        }
        JSONObject result = new JSONObject();
        if (response != null) {
            result.put("code", 0);
            result.put("data", response);
        } else {
            result.put("code", 1);
            result.put("msg", "聊天请求失败");
        }
        return result.toString();
    }
}